import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import { RouteRecordWithMenuItem } from "@/router/types";
import { genMenuItems, genMenuOpenKeys, getPermissionMenuItems } from "@/utils";
import { asyncRoutes } from "@/router";
import { login, loginParams } from "@/api/user";

interface UserState {
  loading: boolean;
  token: string;
  adminName: string;
  role: number;
  checkedKeys: string[];
  menuItems: RouteRecordWithMenuItem[];
}

const userState: UserState = {
  loading: false,
  // token
  token: "",
  adminName: "",
  role: 1,
  // 当前用户的权限数组
  checkedKeys: [], // ['/account/admin-list']
  // 用于渲染左侧菜单的数据
  menuItems: [],
};

const userSlice = createSlice({
  name: "user",
  initialState: userState,
  reducers: {
    loginSuccess(state, { payload }: PayloadAction<any>) {
      state.adminName = payload.adminname;
      state.role = payload.role;
      state.checkedKeys = payload.checkedkeys;
      state.token = payload.token;
    },
    setMenuItems(state) {
      if (state.role === 2) {
        state.menuItems = genMenuItems(asyncRoutes);
      } else {
        // 登录成功之后，修改 state.menuItems
        // 1. 将 payload.checkedkeys 转换成携带有 父路由数据的数组
        // ['/a/b', '/c/d/e'] => ['/a', '/a/b', '/c', '/c/d', '/c/d/e']
        let permissions: string[] = [];
        state.checkedKeys.forEach((key: string) => {
          permissions.push(...genMenuOpenKeys(key));
        });

        // 2. 过滤权限
        //  genMenuItems(asyncRoutes) - 没有判断权限的左侧菜单数据
        //  permissions - 当前用户的权限数据
        state.menuItems = getPermissionMenuItems(
          genMenuItems(asyncRoutes),
          permissions
        );
      }
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(loginAction.pending, (state, action) => {
        // 请求中
        state.loading = true;
      })
      .addCase(loginAction.fulfilled, (state, { payload }) => {
        state.adminName = payload.adminname;
        state.role = payload.role;
        state.checkedKeys = payload.checkedkeys;
        state.token = payload.token;

        // 请求完成
        state.loading = false;

        // 判断当前用户的角色是否是超级管理员
        if (payload.role === 2) {
          state.menuItems = genMenuItems(asyncRoutes);
        } else {
          // 登录成功之后，修改 state.menuItems
          // 1. 将 payload.checkedkeys 转换成携带有 父路由数据的数组
          // ['/a/b', '/c/d/e'] => ['/a', '/a/b', '/c', '/c/d', '/c/d/e']
          let permissions: string[] = [];
          payload.checkedkeys.forEach((key: string) => {
            permissions.push(...genMenuOpenKeys(key));
          });

          // 2. 过滤权限
          //  genMenuItems(asyncRoutes) - 没有判断权限的左侧菜单数据
          //  permissions - 当前用户的权限数据
          state.menuItems = getPermissionMenuItems(
            genMenuItems(asyncRoutes),
            permissions
          );
        }

        localStorage.setItem("token", payload.token);
      })
      .addCase(loginAction.rejected, (state, action) => {
        state.loading = false;
      });
  },
});

export const loginAction = createAsyncThunk("login", async (payload: any) => {
  const { data } = await login(payload);
  return data;
});

export const { loginSuccess, setMenuItems } = userSlice.actions;

export default userSlice.reducer;
